<?php

namespace App\Controller\Admin;

use App\Model\LinksModel;
use App\Setting\LinksSetting;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

use Symfony\Component\HttpFoundation\Request;
use App\Base\BaseController4Admin;
use App\Entity\Links as Entity;

/**
 * @route("/admin/")
 */
class LinksController extends BaseController4Admin
{

    /**
     * @route("Links/add",name="LinksPreAdd")
     */
    public function add()
    {
        $uid = $this->needToBeAdmin();
        //通用代码
        $this->setSetting(new LinksSetting($this->getDoctrine()));
        $entity = "";
        if (!$entity) {$entity = new $this->entitySetting->entityPath();}
        $setting = new LinksSetting($this->getDoctrine());
        $from = $this->getFormCreator()->createAddFrom($entity,$setting->formConfig(),$this->generateUrl("LinksDoAdd"));
        $data = array(
            "title" => $this->entitySetting->entityCnName,
            "show"   => $from->createView(),
            "isAdd"   => true,
        );
        return $this->render("Admin/Links/edit.php.twig",$data);
    }

    /**
     * @route("Links/add/do",name="LinksDoAdd")
     *
     *
     */
    public function doAdd(Request $request)
    {
        $uid = $this->needToBeAdmin();
        $entity = new Entity();
        if (!$entity) {
            $entity = new $this->entitySetting->entityPath();
        }
        $setting = new LinksSetting($this->getDoctrine());
        if ($entity = $this->getFormCreator()->fillEntity($entity,$request,$setting->formConfig())) {
            /**@var $entity Entity*/
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $urlData = [];//传参
            return $this->js_out("保存成功",$this->generateUrl("LinksLists",$urlData));
        } else {
            return $this->js_out("系统错误，请联系管理员",$this->generateUrl("LinksPreAdd"));
        }
    }

    /**
     * @route("Links/edit/{id}",name="LinksPreEdit")
     */
    public function edit(Entity $entity)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new LinksSetting($this->getDoctrine()));
        $setting = new LinksSetting($this->getDoctrine());
        $from = $this->getFormCreator()->createAddFrom($entity,$setting->formConfig(),$this->generateUrl("LinksDoEdit",["id"=>$entity->getId()]));
        $data = array(
            "title" => $this->entitySetting->entityCnName,
            "show"   => $from->createView(),
            "isAdd"   => false,
        );
        return $this->render("Admin/Links/edit.php.twig",$data);
    }

    /**
     * @route("Links/edit/{id}/do",name="LinksDoEdit")
     *
     *
     */
    public function doEdit(Request $request,Entity $entity)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new LinksSetting($this->getDoctrine()));
        $setting = new LinksSetting($this->getDoctrine());
        if ($entity = $this->getFormCreator()->fillEntity($entity,$request,$setting->formConfig())) {
            /**@var $entity Entity*/
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $urlData = [];
            return $this->js_out("保存成功",$this->generateUrl("LinksLists",$urlData));
        } else {
            return $this->js_out("系统错误，请联系管理员",$this->generateUrl("LinksPreEdit",array("id"=>$entity->getId())));
        }
    }

    /**
     * @route("Links",name="LinksLists")
     */
    public function lists()
    {
        $uid = $this->needToBeAdmin();
        //私有部分
        $tools = array();
        //通用部分
        $this->setSetting(new LinksSetting($this->getDoctrine()));
        /*分页配置*/
        if (!$page   = $this->getParamRequired("page")) { $page = 1;}
        $per_page   = $this->entitySetting->perPage;
        $model = new LinksModel($this->getDoctrine());
        $params = array();
        $request = Request::createFromGlobals();
        $txtKeywords = $request->get("txtKeywords");
        if ( $condition = $request->get("cond") ) {
            foreach ( $condition as $key => $val ) {
                if ($val === "") {
                    continue;
                }
                $params["conditions"][$this->entitySetting->table][$key]["eq"]=$val;
            }
        }

        if ($txtKeywords) {
            $params["textKey"] = "%$txtKeywords%";
        }
        $table = str_replace("_","",$this->entitySetting->table);
        $params["groupBy"][$table]=array("id");
        $lists = $model->getAdminLists($params,$page * $per_page - $per_page,$per_page);

        //$lists = $this->getLists($page,$per_page);
        $total = $lists["total"];
        $this->smartFormat($lists["data"]);

        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl("LinksTools"),
            "addUrl"=>$this->generateUrl("LinksPreAdd"),
        );
        $entityCnName = $this->entitySetting->entityCnName;
        return $this->render("Admin/Links/list.php.twig", array(
            'title'     => "$entityCnName 列表",
            "tools"   => $tools,
            'urls'      => $urls,
            'lists'     => $lists["data"],
            'page'      => $this->creatPage($this->generateUrl("LinksLists"),$total,$per_page),
        ));
    }

    /**
     * @route("Links/tools",name="LinksTools")
     */
    public function tools(Request $request)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new LinksSetting($this->getDoctrine()));
        return $this->comTools($request);
    }

    /**
     * @route("Links/copy/{id}",name="LinksDoCopy")
     *
     * @Method({"GET", "POST"})
     */
    public function doCopy(Request $request,Entity $entity)
    {
        $tmp = $entity;
        $tmp = $this->toArray($tmp);
        $en = new Entity();
        foreach ($tmp as $key => $value) {
            if ($key == "id") {continue;}
            $funcGet = "get".ucfirst($key);
            $funcSet = "set".ucfirst($key);
            $en->$funcSet($entity->$funcGet());
        }
        $this->myEm()->persist($en);$this->myEm()->flush();
        return $this->redirectToRoute("LinksLists");
    }

}
